package org.sam.swing;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MyMenuButton extends JToggleButton {
	private static final long serialVersionUID = -1881708725010498435L;


	public MyMenuButton() {
		super();
		this.setText("▼");
		this.setHorizontalTextPosition(SwingConstants.RIGHT);
	}

	public MyMenuButton(final String label) {
		super(label);
		this.setText("▼ " + label);
		this.setHorizontalTextPosition(SwingConstants.RIGHT);
	}

	public void addMenu(JPopupMenu menu) {
		this.setComponentPopupMenu(menu);
	}

	public static void main(String[] args) {

		try {
			// 获取当前操作系统的主题
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
				| UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}

		JFrame frm = new JFrame();
		JPanel p = new JPanel();
		// 创建弹出菜单
		JPopupMenu menu = new JPopupMenu();
		menu.add("第一个菜单项");
		menu.add("第二个菜单项");
		menu.add("第三个个菜单项");
		menu.add("第四个菜单项");

		MyMenuButton button = new MyMenuButton();// 创建按钮
		MyMenuButton button2 = new MyMenuButton("按钮菜单");
		// 把建好的菜单放到按钮上
		button.addMenu(menu);
		button2.addMenu(menu);

		p.add(button);
		p.add(button2);
		frm.add(p);
		frm.setSize(300, 200);
		frm.setLocationRelativeTo(null);
		frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frm.setVisible(true);
	}
}
